package top100;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Godc
 * @description
 */
public class TwoSum {
    public static void main(String[] args) {
        TwoSumSolution twoSumSolution = new TwoSumSolution();
        int[] ints = {3, 2, 4};
        int[] ints1 = twoSumSolution.twoSum(ints, 6);
        System.out.println(Arrays.toString(ints1));
    }
}
class TwoSumSolution {
    /**
     * 空间换时间，利用hash表来存储对应的位置
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}
